package com.zl.awesome.current;

/**
 * for eg: Thread release current lock‘s resource
 * @Author: zl
 * @Date: 2021/9/28 11:37
 */
public class Main {
    //create resource
    private static volatile Object resourceA = new Object();
    private static volatile Object resourceB = new Object();

    public static void main(String[] args) throws InterruptedException{
        //create thread
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //get resourceA's monitor lock
                    synchronized (resourceA){
                        System.out.println("threadA get resourceA lock");
                    //get resourceA's monitor lock
                    synchronized (resourceB){
                        System.out.println("threadA get resourceB lock");
                        System.out.println("threadA release resourceA lock");
                        resourceA.wait();
                    };
                    };
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        //create thread
        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //sleep 1000ms
                    Thread.sleep(1000);
                    //get resourceA's monitor lock
                    synchronized (resourceA){
                        System.out.println("threadB get resourceA lock");
                        System.out.println("threadB get resourceB lock...");
                    synchronized (resourceB){
                        System.out.println("threadB get resourceB lock");
                        System.out.println("threadB release resourceB lock");
                        resourceA.wait();
                    }; };
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        //start Thread
        threadA.start();
        threadB.start();
        //wait thread over
        threadA.join();
        threadB.join();
        System.out.println("main over");
    }
}
